import * as step from '@flow-step/step-toolkit'
import process from 'process'

export class IParams {
    pipelineID!: number

    pipelineName!: string

    buildNumber?: number

    workSpace!: string

    projectDir!: string

    buildJobID!: number

    jenkinsMaster!: string

    jenkinsUsername!: string

    jenkinsPassword!: string

    jenkinsJob!: string

    jenkinsBuildNumber?: number

    params?: string
}

export function getParams(): IParams {
    let params = new IParams()
    params.pipelineID = Number(process.env.PIPELINE_ID)
    params.pipelineName = process.env.PIPELINE_NAME as string
    params.buildNumber = Number(process.env.BUILD_NUMBER)
    params.workSpace = process.env.WORK_SPACE ? process.env.WORK_SPACE as string : "/tmp"
    params.projectDir = process.env.PROJECT_DIR as string
    params.buildJobID = Number(process.env.BUILD_JOB_ID)

    params.jenkinsMaster = process.env.JENKINS_MASTER ? process.env.JENKINS_MASTER as string : 'http://127.0.0.1:9099'
    params.jenkinsUsername = process.env.JENKINS_USERNAME ? process.env.JENKINS_USERNAME as string : "admin"
    params.jenkinsPassword = process.env.JENKINS_PASSWORD ? process.env.JENKINS_PASSWORD as string : "admin"

    // TODO check where are you from?
    const jenkinsJobUrl = process.env.JENKINS_JOB_URL;
    if (jenkinsJobUrl) {
        step.info(`JENKINS_JOB_URL=${jenkinsJobUrl}`);
        const contextPath = jenkinsJobUrl.replace(params.jenkinsMaster, '');
        step.info(`CONTEXT_PATH=${contextPath}`);
        const parts = contextPath.split('/');
        const jenkinsJob = parts.slice(2).join('/');
        step.info(`JENKINS_JOB=${jenkinsJob}`);
        params.jenkinsJob = jenkinsJob
    }

    if (params.jenkinsJob == undefined || params.jenkinsJob == '') {
        params.jenkinsJob = process.env.JENKINS_JOB ? process.env.JENKINS_JOB as string : "demo-job"
    }
    params.jenkinsBuildNumber = process.env.JENKINS_BUILD_NUMBER ? Number(process.env.JENKINS_BUILD_NUMBER) : 1

    params.params = process.env.PARAMS ? process.env.PARAMS as string : "e30k"
    return params
}